package com.yunysha.struts.action;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.yunysha.beans.ModuleBean;
import com.yunysha.beans.UserBean;
import com.yunysha.constants.YunyshaConstants;
import com.yunysha.controller.YunyshaController;
import com.yunysha.struts.actionform.LoginForm;

public class LoginAction extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String forward = null;
		UserBean uBean = null;
		LoginForm loginForm = (LoginForm) form;
		
		request.getSession().removeAttribute(YunyshaConstants.SESSION_USER);
		
		ArrayList<ModuleBean> moduleList = new ArrayList<ModuleBean>();

		String userId = loginForm.getUserName();
		String password = loginForm.getPassword();

		YunyshaController yController = new YunyshaController();

		uBean = yController.validateUserLogin(userId, password);
		if (uBean!=null) {
			
			moduleList = yController.retreiveModuleList(uBean.getUserId());
			uBean.setModuleList(moduleList);
			
			request.getSession().setAttribute(YunyshaConstants.SESSION_USER, uBean);

			forward = YunyshaConstants.SUCCESS;
		} else {
			forward = YunyshaConstants.FAILURE;
			request.setAttribute("errorMsg", "Invalid Username / Password");
		}
		
		return mapping.findForward(forward);
	}
}